package com.may.curator.api;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;

import java.util.List;

/**
 * 利用Curator进行CRUD
 *
 * @author youJie
 * @date 2017-07-28 16:15
 */
public class CuratorClientForTest1212 {

    /**
     * Zookeeper info
     */
    private static final String ZK_ADDRESS = "172.16.0.6:2181,172.16.0.6:2182,172.16.0.6:2183";
    //    private static final String ZK_ADDRESS = "172.16.0.20:2181";
//    private static final String ZK_ADDRESS = "127.0.0.1:2181";
    private static final String ZK_PATH = "/test/com.yunji.fms.settlement.api.pop.IPopSlsettlementInvoiceService/consumers/consumer%3A%2F%2F10.3.17.158%2Fcom.yunji.fms.settlement.api.pop.IPopSettlementInvoiceService%3Fapplication%3Dfms-admin%26category%3Dconsumers%26check%3Dfalse%26default.check%3Dfalse%26default.retries%3D0%26default.timeout%3D16000%26default.version%3D1.0.0%26dubbo%3D2.5.3%26interface%3Dcom.yunji.fms.settlement.api.pop.IPopSettlementInvoiceService%26logger%3Dslf4j%26methods%3DgenerateInvoiceRequest%2Cupdate%2CdeleteById%2CfindExportDetailByPageCount%2CfindInvoiceAndAddressInfo%2CfindOverseasFinanceDetailInfo%2CfindByPageCount%2CfindByPageExport%2CfindExportDetailByPageList%2CfindByPage%2CcancelInvoiceRequest%2CgetById%2CfindByCode%2CfindAllList%2CsubmitInvoiceRequest%2CfindExportDetailByPage%2Cinsert%26pid%3D76475%26revision%3D2.0.6-SNAPSHOT%26side%3Dconsumer%26timestamp%3D";

    private static CuratorFramework client;

    static {
        client = CuratorFrameworkFactory.newClient(
                ZK_ADDRESS,
                new RetryNTimes(10, 5000)
        );
    }

    public static void main(String[] args) throws Exception {
        // 1.Connect to zk
        client.start();

        System.out.println("zk client start successfully!");

        for (int i = 0; i < 1000000; i++) {
            long st = System.currentTimeMillis();
            try {
                // 2.1 Create node
                String data = "hello";

                create(ZK_PATH + st, false);

//                client.create().
//                        creatingParentsIfNeeded()
//                        .withMode(CreateMode.EPHEMERAL)
//                        .forPath(ZK_PATH + st, data.getBytes());

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                print("cost: " + (System.currentTimeMillis() - st) + " ms. ");
            }
        }


    }

    public static void create(String path, boolean ephemeral) {
        int i = path.lastIndexOf('/');
        if (i > 0) {
            create(path.substring(0, i), false);
        }
        if (ephemeral) {
            createEphemeral(path);
        } else {
            createPersistent(path);
        }
    }

    public static void createEphemeral(String path) {
        try {
            client.create().withMode(CreateMode.EPHEMERAL).forPath(path);
        } catch (KeeperException.NodeExistsException e) {
        } catch (Exception e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }

    public static void createPersistent(String path) {
        try {
            client.create().forPath(path);
        } catch (KeeperException.NodeExistsException e) {
        } catch (Exception e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }


//    private static void print(String... cmds) {
//        StringBuilder text = new StringBuilder("$ ");
//        for (String cmd : cmds) {
//            text.append(cmd).append(" ");
//        }
//        System.out.println(text.toString());
//    }

    private static void print(Object result) {
        System.out.println(
                result instanceof byte[]
                        ? new String((byte[]) result)
                        : result);
    }

}
